package com.gzhryc.common.sms;

import org.apache.commons.lang3.StringUtils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.gzhryc.common.logging.Logger;

public class TaobaoSmsHandler implements ISmsHandler{
	
	static Logger log = Logger.getLogger(TaobaoSmsHandler.class);
	
	private String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
	private String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
	
	private String accessKeyId;
	private String accessKeySecret;
	
	private String templateCode;

	//private String smsUrl = "http://gw.api.taobao.com/router/rest"; //"http://eco.taobao.com/router/rest";
	
	public TaobaoSmsHandler(String product,String domain,String accessKeyId,String accessKeySecret,String templateCode){
		this.product = product;
		this.domain = domain;
		this.accessKeyId = accessKeyId;
		this.accessKeySecret = accessKeySecret;
		this.templateCode = templateCode;
	}
	
	public TaobaoSmsHandler(String accessKeyId,String accessKeySecret,String templateCode){
		this.accessKeyId = accessKeyId;
		this.accessKeySecret = accessKeySecret;
		this.templateCode = templateCode;
	}

	@Override
	public boolean send(SmsMessage msg) {
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
	
			IAcsClient acsClient = new DefaultAcsClient(profile);
			
			//组装请求对象
			SendSmsRequest request = new SendSmsRequest();
			//使用post提交
			request.setMethod(MethodType.POST);
			//必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；
			//发送国际/港澳台消息时，接收号码格式为国际区号+号码，如“85200000000”
			request.setPhoneNumbers(msg.getPhone());
			//必填:短信签名-可在短信控制台中找到
			request.setSignName(msg.getSign());
			//可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
			//友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
			if(SmsPhoneVerifyMessage.class.isInstance(msg)) {
				//必填:短信模板-可在短信控制台中找到，发送国际/港澳台消息时，请使用国际/港澳台短信模版
				request.setTemplateCode(templateCode);
				request.setTemplateParam("{\"code\":\""+msg.getContent()+"\"}");
			}else {
				request.setTemplateCode(msg.getTemplateKey());
				request.setTemplateParam(msg.getContent());
			}
			//可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
			//request.setSmsUpExtendCode("90997");
			
			if(StringUtils.isNotBlank(msg.getData())) {
				//可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
				request.setOutId(msg.getData());
			}
			
			//请求失败这里会抛ClientException异常
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				//请求成功
				return true;
			}
		}catch(ClientException e) {
			log.error(e.getMessage(), e);
		}
		
		return false;
		//旧的调用方法，或者APP调用方法
		/*
		TaobaoClient client = new DefaultTaobaoClient(smsUrl,key,secret);
		
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setExtend("");
		req.setSmsType("normal");
		req.setSmsFreeSignName(msg.getSign());
		req.setRecNum(msg.getPhone());

		if(SmsPhoneVerifyMessage.class.isInstance(msg)) {
			req.setSmsTemplateCode("SMS_33545699");
			req.setSmsParamString("{\"code\":\""+msg.getContent()+"\"}");
		}else {
			req.setSmsTemplateCode(msg.getTemplateKey());
			req.setSmsParamString(msg.getContent());
		}
		
		try {
			AlibabaAliqinFcSmsNumSendResponse resp = client.execute(req);
			if(resp != null && StringUtils.isNotBlank(resp.getBody())){
				System.out.println(resp.getBody());
				SmsResponse response = JsonTools.fromJson(resp.getBody(), SmsResponse.class);
				if(response.getError_response() != null && response.getError_response().getCode() != null){
					return false;
				}else{
					return response.getAlibaba_aliqin_fc_sms_num_send_response().getResult().getSuccess();
				}
			}
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return false;
		*/
	}
	
	public static class SmsResponse {
		
		protected SmsResponseErrorData error_response;
		protected SmsResponseData alibaba_aliqin_fc_sms_num_send_response;

		public SmsResponseData getAlibaba_aliqin_fc_sms_num_send_response() {
			return alibaba_aliqin_fc_sms_num_send_response;
		}

		public void setAlibaba_aliqin_fc_sms_num_send_response(SmsResponseData alibaba_aliqin_fc_sms_num_send_response) {
			this.alibaba_aliqin_fc_sms_num_send_response = alibaba_aliqin_fc_sms_num_send_response;
		}

		public SmsResponseErrorData getError_response() {
			return error_response;
		}

		public void setError_response(SmsResponseErrorData error_response) {
			this.error_response = error_response;
		}
	}
	
	public static class SmsResponseErrorData{
		
		protected Integer code;
		protected String msg;
		protected String sub_code;
		protected String sub_msg;
		protected String request_id;
		public Integer getCode() {
			return code;
		}
		public void setCode(Integer code) {
			this.code = code;
		}
		public String getMsg() {
			return msg;
		}
		public void setMsg(String msg) {
			this.msg = msg;
		}
		public String getSub_code() {
			return sub_code;
		}
		public void setSub_code(String sub_code) {
			this.sub_code = sub_code;
		}
		public String getSub_msg() {
			return sub_msg;
		}
		public void setSub_msg(String sub_msg) {
			this.sub_msg = sub_msg;
		}
		public String getRequest_id() {
			return request_id;
		}
		public void setRequest_id(String request_id) {
			this.request_id = request_id;
		}
	}
	
	public static class SmsResponseData {
		
		protected SmsResponseResult result;
		protected String request_id;
		
		public SmsResponseResult getResult() {
			return result;
		}
		public void setResult(SmsResponseResult result) {
			this.result = result;
		}
		public String getRequest_id() {
			return request_id;
		}
		public void setRequest_id(String request_id) {
			this.request_id = request_id;
		}
	}
	
	public static class SmsResponseResult {
		
		protected String err_code;
		protected String model;
		protected Boolean success;
		
		public String getErr_code() {
			return err_code;
		}
		public void setErr_code(String err_code) {
			this.err_code = err_code;
		}
		public String getModel() {
			return model;
		}
		public void setModel(String model) {
			this.model = model;
		}
		public Boolean getSuccess() {
			return success;
		}
		public void setSuccess(Boolean success) {
			this.success = success;
		}
	}

	@Override
	public String getType() {
		return "Taobao";
	}

}
